package org.jeecg.common.util.sm.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class FileUtils {
    public static String copyFile(String sourcePath, String cachePath) {
        try {
            File file = new File(cachePath);
            if (!file.exists()) {
                file.mkdirs();
            }
            String fileName = new File(sourcePath).getName();
            String targetPath = cachePath + File.separator + System.currentTimeMillis() + fileName;
            Files.copy(new File(sourcePath).toPath(), new File(targetPath).toPath(), StandardCopyOption.REPLACE_EXISTING);
            return targetPath;
        } catch (IOException e) {
            throw new RuntimeException(e);

        }
    }

    public static void compressFiles(List<String> filePaths, String outputZipFilePath) {
        boolean result = true;
        File outFile = new File(outputZipFilePath);
        if (!outFile.getParentFile().exists()) {
            result = outFile.getParentFile().mkdirs();
        }
        if (!result) {
            System.out.println(false);
            return;
        }
        try (ZipOutputStream zipOut = new ZipOutputStream(Files.newOutputStream(Paths.get(outputZipFilePath)))) {
            for (String filePath : filePaths) {
                File fileToZip = new File(filePath);
                FileInputStream fis = new FileInputStream(fileToZip);
                ZipEntry zipEntry = new ZipEntry(fileToZip.getName());
                zipOut.putNextEntry(zipEntry);
                byte[] bytes = new byte[1024];
                int length;
                while ((length = fis.read(bytes)) >= 0) {
                    zipOut.write(bytes, 0, length);
                }
                fis.close();
            }
            System.out.println(true);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static String getEncryptedFileName(String fileName) {
        return (new File(fileName).getName()) + ".enc";
    }
}
